package com.shire.shire_interface.common.utils;

import java.text.DecimalFormat;
import java.util.Map;

public class MathUtils {
    private static DecimalFormat df = new DecimalFormat("0.00");
    ;

    public static int getNullValue(Integer i, int def) {
        if (i == null) return def;
        return i;
    }

    public static long getNullValue(Long i, long def) {
        if (i == null) return def;
        return i;
    }

    public static int getNullIntValue(Object i, int def) {
        if (i == null) return def;
        try {
            return ((Number) i).intValue();
        } catch (Exception e) {
            return def;
        }
    }

    public static long getNullLongValue(Object i, long def) {
        if (i == null) return def;
        return ((Number) i).longValue();
    }

    public static int incrMapValue(Map<String, Object> map, String key, int incrValue) {
        int value = getNullIntValue(map.get(key), 0) + incrValue;
        map.put(key, value);
        return value;
    }

    public static int incrMapValue(Map<Integer, Integer> map, Integer key, int incrValue) {
        int value = getNullIntValue(map.get(key), 0) + incrValue;
        map.put(key, value);
        return value;
    }

    public static int incrMapValue(Map<String, Object> map, String key, Number incrValue) {
        int value = getNullIntValue(map.get(key), 0) + incrValue.intValue();
        map.put(key, value);
        return value;
    }

    public static int getMapIntValue(Map<String, Object> map, String key, int def) {
        Number n = (Number) map.get(key);
        return n != null ? n.intValue() : def;
    }

    public static Long getMapLongValue(Map<String, Object> map, String key, Long def) {
        Number n = (Number) map.get(key);
        return n != null ? n.longValue() : def;
    }

    public static String formatFloat2(Object f) {
        return df.format(f);
    }

    public static String formatRate(Number son, Number total) {
        if (total.intValue() == 0 || son.intValue() == 0) return "0.00%";
        return formatFloat2(son.intValue() * 100.0f / total.intValue()) + "%";

    }
}
